package com.shujia.spark.stream

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo2UpdateStateByKey {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local[2]")
    conf.setAppName("stream")

    val sc = new SparkContext(conf)

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    //设置checkpoint路径
    ssc.checkpoint("data/checkpoint")

    /**
     * 读取socket中的数据
     */
    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    val wordsDS: DStream[String] = linesDS.flatMap(_.split(">"))

    val kvDS: DStream[(String, Int)] = wordsDS.map((_, 1))

    /**
     *
     * @param seq   : 当前批次一个key所有的value
     * @param state : 上一个批次一个key计算的结果（单词数量），上一次可能没有
     * @return 返回当前批次汇总的结果
     */
    def updateFun(seq: Seq[Int], state: Option[Int]): Option[Int] = {
      //计算当前批次单词的数量
      val currCount: Int = seq.sum
      //获取上一个批次单纯的数量
      val count: Int = state.getOrElse(0)

      //当前批次单词的数量加上之前批次单词的数量得到总的数量
      Option(currCount + count)
    }

    /**
     * updateStateByKey: 有状态算子，每一次计算都基于上一次计算结果进行计算
     */

    val countDS: DStream[(String, Int)] = kvDS.updateStateByKey(updateFun)


    countDS.print()


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
